// 重写 XMLHttpRequest
(function (open) {
    XMLHttpRequest.prototype.open = function (method, url, async, user, pass) {
        this.addEventListener('load', function () {
            if (this.status === 200) {
                // 根据实际情况判断是否是需要的数据接口
                if (url.includes('your-target-api-url')) {
                    try {
                        const responseData = JSON.parse(this.responseText);
                        // 发送消息给 background.js 处理数据
                        chrome.runtime.sendMessage({ action: 'processAjaxData', data: responseData }, (response) => {
                            if (chrome.runtime.lastError) {
                                console.error('发送消息到 background.js 出错:', chrome.runtime.lastError.message);
                            } else {
                                console.log('background.js 响应:', response);
                            }
                        });
                    } catch (error) {
                        console.error('解析 AJAX 响应数据出错:', error);
                    }
                }
            }
        });
        open.call(this, method, url, async, user, pass);
    };
})(XMLHttpRequest.prototype.open);

// 重写 fetch
const originalFetch = window.fetch;
window.fetch = async function (input, init) {
    const response = await originalFetch(input, init);
    if (response.ok) {
        const url = typeof input === 'string' ? input : input.url;
        if (url.includes('your-target-api-url')) {
            try {
                const responseData = await response.json();
                // 发送消息给 background.js 处理数据
                chrome.runtime.sendMessage({ action: 'processAjaxData', data: responseData }, (response) => {
                    if (chrome.runtime.lastError) {
                        console.error('发送消息到 background.js 出错:', chrome.runtime.lastError.message);
                    } else {
                        console.log('background.js 响应:', response);
                    }
                });
            } catch (error) {
                console.error('解析 fetch 响应数据出错:', error);
            }
        }
    }
    return response;
};

// 监听 DOM 变化
const table = document.querySelector('table');
if (table) {
    const observer = new MutationObserver((mutationsList) => {
        for (const mutation of mutationsList) {
            if (mutation.type === 'childList') {
                // 表格内容发生变化，进行数据爬取
                const allData = [];
                const rows = table.querySelectorAll('tr');
                rows.forEach(row => {
                    const rowData = [];
                    const cells = row.querySelectorAll('td, th');
                    cells.forEach(cell => {
                        rowData.push(cell.textContent.trim());
                    });
                    allData.push(rowData);
                });
                // 发送消息给 background.js 处理表格数据
                chrome.runtime.sendMessage({ action: 'processTableData', data: allData }, (response) => {
                    if (chrome.runtime.lastError) {
                        console.error('发送表格数据到 background.js 出错:', chrome.runtime.lastError.message);
                    } else {
                        console.log('background.js 对表格数据的响应:', response);
                    }
                });
            }
        }
    });

    const config = { childList: true, subtree: true };
    observer.observe(table, config);
}

// 监听来自 popup.js 的消息
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
    if (message.action === 'startCrawling') {
        console.log('开始爬取数据...');
        // 模拟异步操作
        setTimeout(() => {
            sendResponse({ status: 'success', message: '数据爬取已启动' });
        }, 1000);
        return true;
    }
    // 如果消息类型未知，返回错误响应
    sendResponse({ status: 'error', message: '未知消息类型' });
    return false;
});    